package com.googlecode.cswish.struts;

import static com.googlecode.cswish.struts.Action.ADD;
import static com.googlecode.cswish.struts.Action.DELETE;
import static com.googlecode.cswish.struts.Action.LIST;
import static com.googlecode.cswish.struts.Action.SEARCH;
import static com.googlecode.cswish.struts.Action.UPDATE;
import static com.googlecode.cswish.struts.Action.VIEW;

import java.lang.reflect.Method;

import com.googlecode.cswish.annotation.Rest;
import com.googlecode.cswish.util.FrameConstant;

/**
 * A help object to check the rest type
 * 	 
 * @author Jerry.feng Date: 22/09/2008
 */
public class RestAction {

	public static boolean isCreate(Class<?> action, String method) {
		return match(action, method, ADD);
	}
	
	public static boolean match(Class<?> action, String method, String ... matchValues) {
		// 1. check according to the naming rule
		if (method != null) {
			if (match(method, matchValues)) {
				return true;
			}
		}
		
		if (action != null) {
			for (Method theMethod : action.getMethods()) {
				if (theMethod.getName().equals(method)) {
					Rest rest = theMethod.getAnnotation(Rest.class);
					if (rest != null) {
						String type = rest.type();
						return match(type, matchValues);
					}
					break;
				}
			}
		}
		
		return false;
	}
	
	private static boolean match(String value, String ... matchValues) {
		int toffset = 0;
		if (value.startsWith(FrameConstant.ACTION_PREPARE)) {
			toffset = FrameConstant.ACTION_PREPARE.length();
		}
		for (String matchValue : matchValues) {
			if (value.startsWith(matchValue, toffset)) {
				return true;
			}
		}
		return false;
	}
	
	public static boolean isRead(Class<?> action, String method) {
		return match(action, method, VIEW, SEARCH, LIST);
	}
	
	
	public static boolean isUpdate(Class<?> action, String method) {
		return match(action, method, UPDATE);
	}
	
	public static boolean isDelete(Class<?> action, String method) {
		return match(action, method, DELETE);
	}
}